import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import _ from 'lodash';
import qs from 'qs';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { getAddressNameByCode, addTab } from '@/utils/utils';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Card,
  Row,
  Col,
  Select,
  Cascader,
  Button,
  Divider,
  Dropdown,
  Menu,
  Table,
  Modal,
  Timeline,
  Tooltip,
} from 'antd';
import { DownOutlined } from '@ant-design/icons';

import '@ant-design/compatible/assets/index.css';

const { Option } = Select;
const { Item } = Form;

const realName = ['禁用', '强制实名', '非强制实名'];

const operTitle = ['canSending', 'needIdcertify', 'deliIdcertifyMode'];
const operCopywrit = ['寄件功能', '寄件实名制', '投递实名制'];

const { pathname } = window.location;

interface AreaFunctionListProps extends FormComponentProps {
  dispatch: Dispatch;
  loading: boolean;
  dataInfo: any;
  gardenList: any;
  INITINFO: any;
  location: any;
  screen: string;
}

interface AreaFunctionListState {
  searchValues: any;
  funcName: string;
  operVisible: boolean;
  pageIndex:number;
  pageSize:number;
  operValues: {
    id: number;
    index: number;
    canSending: number;
    needIdcertify: number;
    deliIdcertifyMode: number;
  };
  logVisible: boolean;
  logValues: {
    createUser: string;
    createTime: string;
    updateUser: string;
    updateTime: string;
  };
  delVisible: boolean;
  delId: number;
  rowId:number;
}

@connect(
  ({
    areaFunctionList: { dataInfo, gardenList },
    common: { INITINFO },
    global: { screen },
    loading,
  }: any) => ({
    dataInfo,
    gardenList,
    INITINFO,
    screen,
    loading: loading.effects['areaFunctionList/fetch'],
  }),
)

class AreaFunctionListElem extends React.Component<AreaFunctionListProps, AreaFunctionListState> {
  columns: any = [
    {
      title: '省/直辖市',
      dataIndex: 'pareaCode',
      width: 100,
      render: (text: string, row: any) => getAddressNameByCode({
        pareaCode: row.pareaCode,
        caredCode: row.careaCode,
        dareaCode: row.dareaCode,
      })[0] || '--',
    },
    {
      title: '市/地级区',
      dataIndex: 'careaCode',
      width: 94,
      render: (text: string, row: any) => getAddressNameByCode({
        pareaCode: row.pareaCode,
        caredCode: row.careaCode,
        dareaCode: row.dareaCode,
      })[1] || '--',
    },
    {
      title: '县级市/区',
      dataIndex: 'dareaCode',
      width: 94,
      render: (text: string, row: any) => getAddressNameByCode({
        pareaCode: row.pareaCode,
        caredCode: row.careaCode,
        dareaCode: row.dareaCode,
      })[2] || '--',
    },
    {
      title: '社区名称',
      dataIndex: 'gardenName',
      width: 140,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text || '--'}</div>
        </Tooltip>
      ),
    },
    {
      title: '社区类型',
      dataIndex: 'gardenType',
      width: 88,
      render: (text: number) => {
        const { INITINFO: { gardenType } } = this.props;

        let value = '';
        gardenType.map((item: any) => {
          if (text === item.mCode) value = item.codeName;
          return false;
        });

        return value || '不限';
      },
    },
    {
      title: '取件实名制',
      dataIndex: 'pickupIdcertifyMode',
      width: 100,
      render: (text: number) => realName[text],
    },
    {
      title: '社区柜体寄件功能',
      dataIndex: 'canSending',
      width: 140,
      render: (text: number) => (text ? '启用' : '禁用'),
    },
    {
      title: '寄件实名制',
      dataIndex: 'needIdcertify',
      width: 100,
      render: (text: number) => (text ? '启用' : '禁用'),
    },
    {
      title: '操作',
      dataIndex: 'id',
      fixed: 'right',
      width: 120,
      render: (text: number, record: any) => (
        <>
          <span className="operLink" onClick={() => this.handleEditArea(text)}>
            编辑
          </span>
          <Divider type="vertical" />
          <span className="operLink" onClick={() => this.handleChangeDelModal(true, text)}>
            删除
          </span>
          <Divider type="vertical" />
          <Dropdown arrow overlay={() => this.menu(record)}>
            <span className="operLink">
              更多 <DownOutlined />
            </span>
          </Dropdown>
        </>
      ),
    },
  ];

  state: AreaFunctionListState = {
    searchValues: {},
    pageIndex: 1,
    pageSize: 20,
    funcName: '',
    operVisible: false,
    operValues: {
      id: 0,
      index: 0,
      canSending: 0, // 寄件功能
      needIdcertify: 0, // 寄件实名制
      deliIdcertifyMode: 0, // 投递实名制
    },
    logVisible: false,
    logValues: {
      createUser: '',
      createTime: '',
      updateUser: '',
      updateTime: '',
    },
    delVisible: false,
    delId: 0,
    rowId: 0,
  };

  static getDerivedStateFromProps(nextProps: any, preState: any) {
    const { funcName } = preState;
    const { location: { query } } = nextProps;
    const { pageIndex, pageSize, ...values } = query;
    return {
      searchValues: {
        ...values,
        status: values.status || '-1',
      },
      pageIndex: Number(pageIndex) || 1,
      pageSize: Number(pageSize) || (nextProps.screen === 'sm' ? 100 : 20),
      funcName: values.funcName || funcName,
    };
  }

  componentDidMount() {
    this.setFieldsValue();
    this.fetchDataValues();
    this.handleValidation();
    this.fetchAction('common/fetchGardenType');
    this.fetchAction('common/fetchAddressList');

    this.fetchAction('fetchGarden', {});
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues, pageIndex, pageSize } = this.state;
    if (!_.isEqual(searchValues, prevState.searchValues)
      || pageIndex !== prevState.pageIndex
      || pageSize !== prevState.pageSize
    ) {
      this.setFieldsValue();
      this.fetchDataValues();
    }
  }

  componentWillUnmount() {
    this.fetchAction('clear');
  }

  setFieldsValue = () => {
    // 设置表单
    const { searchValues } = this.state;
    const params = this.turnValuesType(searchValues);
    const { form: { setFieldsValue } } = this.props;
    setFieldsValue(params);
  };

  turnValuesType = (values: any) => {
    const {
      provinceCode,
      cityCode,
      countyCode,
      ...query
    } = values;
    const area = [provinceCode, cityCode, countyCode];
    const params = {
      ...query,
      areaCodes: area.filter((item: any) => item),
    };

    return params;
  };

  fetchDataValues = () => {
    const params = this.getQueryParams();
    this.fetchAction('fetch', params);
  };

  getQueryParams = () => {
    const { searchValues, pageIndex, pageSize }: any = this.state;
    const { funcName, status, ...query } = searchValues;
    const params = {
      ...query,
      pageIndex,
      pageSize,
    };

    if (funcName) params[funcName] = status;
    return params;
  };

  menu = (row: any) => (
    <Menu>
      <Menu.Item className="operLink" onClick={() => this.handleChangeOperModal(true, 0, row)}>
        {row.canSending === 1 ? '禁用' : '启用'}寄件功能
      </Menu.Item>
      <Menu.Item
        className={row.canSending && 'operLink'}
        disabled={Boolean(!row.canSending)}
        onClick={() => this.handleChangeOperModal(true, 1, row)}
      >
        {row.needIdcertify === 1 ? '禁用' : '启用'}寄件实名制
      </Menu.Item>
      <Menu.Item className="operLink" onClick={() => this.handleChangeLogModal(true, row)}>
        操作日志
      </Menu.Item>
    </Menu>
  );

  /**
   * 新建区域
   */
  handleAddArea = () => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '新建区域',
      url: '/business/areaFunction/list/add',
    });
  };

  /**
   * 编辑区域
   */
  handleEditArea = (id: number) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '编辑区域',
      url: `/business/areaFunction/list/edit?id=${id}`,
    });
  };

  handleChangeOperModal = (operVisible: boolean, index: number = 0, row: any = {}) => {
    this.setState({
      operVisible,
      operValues: {
        id: row.id,
        index,
        canSending: row.canSending ? 0 : 1,
        needIdcertify: row.needIdcertify ? 0 : 1,
        deliIdcertifyMode: row.deliIdcertifyMode ? 0 : 1,
      },
    });
  };

  handleOperSubmit = () => {
    const { searchValues, operValues } = this.state;
    const params = {
      id: operValues.id,
      index: operValues.index,
      search: searchValues,
    };
    params[operTitle[operValues.index]] = operValues[operTitle[operValues.index]];
    this.fetchAction('operAction', params);
    this.handleChangeOperModal(false);
  };

  handleChangeDelModal = (delVisible: boolean, delId: number = 0) => {
    this.setState({ delVisible, delId });
  };

  handleDelSubmit = () => {
    const { searchValues: search, delId: id } = this.state;
    const params = { search, id };
    this.fetchAction('fetchDel', params);

    this.handleChangeDelModal(false);
  };

  handleChangeLogModal = (logVisible: boolean, row: any = {}) => {
    this.setState({
      logVisible,
      logValues: {
        createUser: row.createUser,
        createTime: row.createTime,
        updateUser: row.updateUserName,
        updateTime: row.updateTime,
      },
    });
  };

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((errors, values) => {
      if (errors) return;

      const { areaCodes, ...params } = values;
      const query = {
        ...params,
        pageIndex: 1,
        pageSize: 20,
      };

      if (areaCodes[0]) [query.provinceCode] = [areaCodes[0]];
      if (areaCodes[1]) [query.cityCode] = [areaCodes[1]];
      if (areaCodes[2]) [query.countyCode] = [areaCodes[2]];

      const { dispatch } = this.props;
      addTab(dispatch, {
        name: '区域功能管理',
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  };

  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    this.fetchAction('clearGarden');

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '区域功能管理',
      url: pathname,
      isTopMenu: true,
    });

    this.setState({ funcName: '' });
  };

  handleSelectFuncName = (funcName: string) => {
    // 选择功能
    const { form: { setFieldsValue } } = this.props;
    setFieldsValue({ status: '-1' });

    this.setState({ funcName });
  };

  handleValidation = () => {
    const { form: { getFieldValue } } = this.props;
    const value = getFieldValue('areaCodes') || [];

    if (value.length) {
      const params = {
        pareaCode: value[0],
        careaCode: value[1],
        dareaCode: value[2],
      };
      this.fetchAction('fetchGarden', params);
    } else {
      this.fetchAction('fetchGarden', {});
    }
  };

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { searchValues } = this.state;
    const query = { ...searchValues, pageIndex, pageSize };
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '区域功能管理',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };


  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  fetchAction = (typeName: string, payload: any = {}) => {
    const type = typeName.indexOf('common') >= 0
      ? typeName : `areaFunctionList/${typeName}`;
    const { dispatch } = this.props;
    dispatch({ type, payload });
  };

  render() {
    const {
      pageIndex,
      pageSize,
      funcName,
      operVisible,
      operValues,
      logVisible,
      logValues,
      delVisible,
    } = this.state;

    const {
      form: { getFieldDecorator },
      dataInfo,
      gardenList,
      INITINFO: { gardenType, addressList },
      screen,
      loading,
    } = this.props;

    const dataSource = dataInfo ? dataInfo.list : [];
    const pagination: object = {
      total: dataInfo ? dataInfo.count : 0,
      current: pageIndex,
      pageSize,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      showTotal: () => `共${dataInfo.count || 0}条数据`,
      onChange: this.onSelectChange,
      onShowSizeChange: this.onSelectChange,
    };

    if (screen === 'sm' || screen === 'lg') {
      delete this.columns[this.columns.length - 1].fixed;
    } else if (screen === 'md') {
      this.columns[this.columns.length - 1].fixed = 'right';
    }

    return (
      <>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          <Form className="tableListForm" onSubmit={this.handleSearch}>
            <Row gutter={12}>
              <Col md={6} sm={24}>
                <Item label="社区类型" colon={false}>
                  {getFieldDecorator('gardenType')(
                    <Select placeholder="请选择">
                      {gardenType.map((item: any) => (
                        <Option value={String(item.mCode)} key={item.mCode}>{item.codeName}</Option>
                      ))}
                    </Select>,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="　省市区" colon={false}>
                  {getFieldDecorator('areaCodes')(
                    <Cascader options={addressList} placeholder="请选择" changeOnSelect />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="社区名称" colon={false}>
                  {getFieldDecorator('gardenId')(
                    <Select
                      showSearch
                      allowClear
                      placeholder="请选择"
                      onFocus={this.handleValidation}
                      filterOption={(input: any, option: any) => (
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      )}
                    >
                      {gardenList.map((item: any) => (
                        <Option value={String(item.id)} key={item.id}>{item.name}</Option>
                      ))}
                    </Select>,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="功能筛选" colon={false}>
                  {getFieldDecorator('funcName')(
                    <Select placeholder="请选择" onChange={this.handleSelectFuncName}>
                      <Option value="">请选择</Option>
                      <Option value="canSending">寄件功能</Option>
                      <Option value="needIdcertify">寄件实名制</Option>
                      <Option value="pickupIdcertifyMode">取件实名制</Option>
                      <Option value="deliIdcertifyMode">投递实名制</Option>
                    </Select>,
                  )}
                </Item>
              </Col>
            </Row>
            <Row gutter={12} justify="space-between">
              <Col md={6} sm={24}>
                <Item label="　　状态" colon={false}>
                  {getFieldDecorator('status')(
                    funcName === 'pickupIdcertifyMode' ? (
                      <Select placeholder="请选择" disabled={Boolean(!funcName)}>
                        <Option value="-1">请选择</Option>
                        <Option value="0">禁用</Option>
                        <Option value="1">强制</Option>
                        <Option value="2">非强制</Option>
                      </Select>
                    ) : (
                      <Select placeholder="请选择" disabled={Boolean(!funcName)}>
                        <Option value="-1">请选择</Option>
                        <Option value="0">禁用</Option>
                        <Option value="1">启用</Option>
                      </Select>
                    ),
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <div className="flexFeView">
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="smallButton"
                  >
                    查询
                  </Button>
                  <Button
                    type="primary"
                    className="addButton smallButton marginL16"
                    onClick={this.handleReset}
                  >
                    重置
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              className="smallButton"
              onClick={this.handleAddArea}
            >
              新建区域
            </Button>
          </div>
          <Table
            rowKey="id"
            tableLayout="fixed"
            className="statementTable tableHeight60"
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
            loading={loading}
            scroll={{ x: 1400 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>

        <Modal
          title="操作日志"
          visible={logVisible}
          footer={null}
          onCancel={() => this.handleChangeLogModal(false)}
        >
          <Timeline style={{ marginBottom: -20 }}>
            <Timeline.Item>最近操作人：{logValues.updateUser}</Timeline.Item>
            <Timeline.Item>最近操作时间：{logValues.updateTime}</Timeline.Item>
            <Timeline.Item>创建时间：{logValues.createTime}</Timeline.Item>
          </Timeline>
        </Modal>

        <Modal
          title="确认提示"
          visible={operVisible}
          destroyOnClose
          onOk={this.handleOperSubmit}
          onCancel={() => this.handleChangeOperModal(false)}
        >
          <p>
            确定{operValues[operTitle[operValues.index]] ? '启用' : '禁用'}
            {operCopywrit[operValues.index]}?
          </p>
        </Modal>

        <Modal
          title="确认提示"
          visible={delVisible}
          onOk={this.handleDelSubmit}
          onCancel={() => this.handleChangeDelModal(false)}
        >
          <p>确定删除当前区域?</p>
        </Modal>
      </>
    );
  }
}

export default Form.create<AreaFunctionListProps>()(AreaFunctionListElem);
